'use strict';

const semver = require('semver') // 版本比对
const LOWEST_NODE_VERSION = '12.0.0'
const colors = require('colors/safe')
const {isObject} = require('@baseh-cli-dev/utils')

class Command {
  constructor (argv) {
    // console.log('init command', argv)
    if (!argv) {
      throw new Error('参数不能为空')
    }
    if (!Array.isArray(argv)) {
      throw new Error('参数参数必须是array')
    }
    this._argv = argv
    let runner = new Promise((resolve, reject) => {
      let chain = Promise.resolve();
      chain = chain.then(() => this.checkNodeVersion())
      chain = chain.then(() => this.initArgs())
      chain = chain.then(() => this.init())
      chain = chain.then(() => this.exec())
      chain.catch(err => {
        console.log(err.message)
      })
    })
  }

  checkNodeVersion () {
    // 获取当前node版本号
    const currentVersion = process.version
    // 比对最低版本号
    const lowestVersion = LOWEST_NODE_VERSION
    // semver
    if (!semver.gte(currentVersion, lowestVersion)) {
      throw new Error(colors.red(`baseh-cli 需要安装 v${lowestVersion} 以上版本Node.js`))
    }
  }

  initArgs () {
    this._cmd = this._argv[this._argv.length - 1]
    this._argv = this._argv.slice(0, this._argv.length - 1)
  }

  init () {
    throw new Error('init 必须实现')
  }

  exec () {
    throw new Error('exec 必须实现')
  }
}

module.exports = Command